package com.yuzhi.master.system;

import cn.dev33.satoken.annotation.SaIgnore;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.crypto.SecureUtil;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonObject;
import com.google.gson.internal.LinkedTreeMap;
import com.yunlizhihui.common.model.vo.JsonResult;
import com.yuzhi.common.contant.Constants;
import com.yuzhi.common.core.domain.ApiResult;
import com.yuzhi.common.core.domain.entity.SysMenu;
import com.yuzhi.common.core.domain.entity.SysUser;
import com.yuzhi.common.core.domain.model.LoginBody;
import com.yuzhi.common.core.domain.model.LoginUser;
import com.yuzhi.common.core.domain.model.SmsLoginBody;
import com.yuzhi.common.core.domain.model.XcxLoginUser;
import com.yuzhi.common.enums.DeviceTypeEnum;
import com.yuzhi.common.exception.user.UserException;
import com.yuzhi.common.helper.LoginHelper;
import com.yuzhi.framework.config.properties.AesKeyPropertiesConfig;
import com.yuzhi.framework.config.properties.AppLoginProperties;
import com.yuzhi.framework.config.properties.UniLoginProperties;
import com.yuzhi.system.domain.vo.RouterVo;
import com.yuzhi.system.service.ISysMenuService;
import com.yuzhi.system.service.ISysUserService;
import com.yuzhi.system.service.SysLoginService;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import javax.validation.constraints.NotBlank;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 登录验证
 *
 * @author auto
 */
@Validated
@RequiredArgsConstructor
@RestController
public class SysLoginController {

    private final SysLoginService loginService;
    private final ISysMenuService menuService;
    private final ISysUserService userService;
    private RestTemplate restTemplate = new RestTemplate();
    @Autowired
    private AesKeyPropertiesConfig aesKeyPropertiesConfig;
    private final AppLoginProperties appLoginProperties;

    private final UniLoginProperties uniLoginProperties;



/*    public static void main(String[] args) {
        UniLoginProperties uniLoginProperties = new UniLoginProperties();
        Gson gson = new GsonBuilder().create();
        RestTemplate restTemplate = new RestTemplate();
        String url = uniLoginProperties.getLoginUrl() + "/uniauth/auth/getUserInfoByTicket";
        String queryParm = "clientId=" + uniLoginProperties.getClientId() + "&ticket=" + "Yzg4NDE2NTAwMmYwNGQ2ODljMzJhODg3NmY1MTdhMWQ=";
        url = url +  "?" + queryParm;

        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.setContentType(MediaType.APPLICATION_JSON);

        HttpEntity<UnifiedLogin> requestEntity = new HttpEntity<>(null, httpHeaders);
        ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.GET, requestEntity, String.class);
        System.out.println(response);

        JsonResult result = gson.fromJson(response.getBody(), JsonResult.class);


        if(response.getStatusCode() == HttpStatus.OK){
            String username = (String) ((LinkedTreeMap) ((LinkedTreeMap) result.getResult()).get("userInfo")).get("username");
            System.out.println("Username: " + username);
            System.out.println(result.getResult());
        }else{
            System.out.println(response);
        }
    }*/

    /**
     * 登录方法
     *
     * @param loginBody 登录信息
     * @return 结果
     */
    @SaIgnore
    @PostMapping("/loginMl")
    public ApiResult<Map<String, Object>> loginMl(@Validated @RequestBody LoginBody loginBody) {
        Map<String, Object> ajax = new HashMap<>();
        // 生成令牌
        String token = loginService.login( "admin" , "WanG%@0902v.ling***", loginBody.getCode(),
                loginBody.getUuid());
        ajax.put(Constants.TOKEN, token);
        return ApiResult.ok(ajax);
    }

    public static void main(String[] args) {

        AppLoginProperties appLoginProperties = new AppLoginProperties();
        appLoginProperties.setAppkey("66c409e1-c7ec-4889-bd0c-3984d61ef4e5");
        appLoginProperties.setUrl("http://192.168.10.233:9520");
        appLoginProperties.setAppsecret("eb363bc8-0824-4f8f-bb56-39189d301a8e");
        Gson gson = new GsonBuilder().create();
        RestTemplate restTemplate = new RestTemplate();

        //获取code
        String code ="" ;
        String urlCode = appLoginProperties.getUrl() + "/app/ebu/api/v1/getCode";

        HttpHeaders httpHeadersCode = new HttpHeaders();
        httpHeadersCode.setContentType(MediaType.APPLICATION_JSON);
        httpHeadersCode.set("Authorization","Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJhdWQiOiJhcGkiLCJzdWIiOiJkN2MzODNjNi00ZjA0LTQ3NDUtOWVlZS0xOGU5YTNiMDQzM2UiLCJuYmYiOjE3MzM4ODgyMzcsInN5c0lkIjoiM2Q1YmM0OWUtYTg3My00MjM2LWE0NzItOGU1ZjZlODEyM2U1IiwiaGFzaENvZGUiOiJmOWM2Y2E5MDMyZmI2NWVhZGEwNzBmMzRlZmExNTNhYjU0NzQ0N2UwIiwiaXNzIjoiaXN0cm9uZyIsInRlbmFudElkIjoiMzE0OTdjMjEtNGJlNy00NWRkLWFjZjYtZDg5NmJmNWFlYWY0IiwiZGVwSWQiOiI5YmY3Mzc5Ny1kMDBjLTRlOGUtYmNmNi1jNWUyZTU4ZDM0ZWIiLCJleHAiOjE3MzkwNzIyMzcsImlhdCI6MTczMzg4ODIzNywidXNlcklkIjoiZDdjMzgzYzYtNGYwNC00NzQ1LTllZWUtMThlOWEzYjA0MzNlIiwianRpIjoiZmQyYTE1ODUtZmYxMS00NDY0LWI0ZWUtYTc5OWIzN2IwZGRhIn0.tBPyV6VddkxuWyDG8gk7qQ3s1KfveVYQ86GO_1rNaGk");

       /* String accessToken ="" ;
        String url = appLoginProperties.getUrl() + "/api/open/v1/gettoken";
        String queryParm = "appkey=" + appLoginProperties.getAppkey() + "&appsecret=" + appLoginProperties.getAppsecret();
        url = url +  "?" + queryParm;
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.setContentType(MediaType.APPLICATION_JSON);
        HttpEntity<UnifiedLogin> requestEntity = new HttpEntity<>(null, httpHeaders);
        ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.GET, requestEntity, String.class);
        System.out.println(response);

        if(response.getStatusCode() == HttpStatus.OK){
            Result result = gson.fromJson(response.getBody(), Result.class);
            if (result != null && result.getData() != null) {
                accessToken =result.getData().getAccessToken();
                System.out.println("AccessToken: " +  accessToken);
            } else {
                System.err.println("Failed to parse JSON or data is null");
            }
        }else{
            System.out.println(response);
        }


        String userName ="";
        String urlInfo = appLoginProperties.getUrl() + "/api/open/v1/oauth2/getuserinfo";
        String queryParmcode = "code=" +code;
        urlInfo = urlInfo +  "?" + queryParmcode;

        HttpHeaders httpHeadersInfo= new HttpHeaders();
        httpHeadersInfo.setContentType(MediaType.APPLICATION_JSON);
        httpHeadersInfo.set("EP-ACCESS-TOKEN",accessToken);
        HttpEntity<UnifiedLogin> requestEntityInfo = new HttpEntity<>(null, httpHeadersInfo);
        ResponseEntity<String> responseInfo = restTemplate.exchange(urlInfo, HttpMethod.GET, requestEntityInfo, String.class);
        if(responseInfo.getStatusCode() == HttpStatus.OK){
            Result result = gson.fromJson(responseInfo.getBody(), Result.class);
            if (result != null && result.getData() != null) {
                userName =result.getData().getUserName();
                System.out.println("userName: " +  userName);
            } else {
                System.err.println("Failed to parse JSON or data is null");
            }
        }else{
            System.out.println(response);
        }*/
    }

    @SaIgnore
    @PostMapping("/appLogin")
    public ApiResult<Map<String, Object>> appLogin(@Validated @RequestBody LoginBody loginBody) {
        Map<String, Object> ajax = new HashMap<>();
        // 生成令牌
        String token = loginService.login(loginBody.getUsername(), loginBody.getPassword(), loginBody.getCode(),
                loginBody.getUuid());
        ajax.put(Constants.TOKEN, token);
        return ApiResult.ok(ajax);
    }


    /**
     * 登录方法
     *
     * @param loginBody 登录信息
     * @return 结果
     */
    @SaIgnore
    @PostMapping("/login")
    public ApiResult<Map<String, Object>> login(@Validated @RequestBody LoginBody loginBody) {
        Map<String, Object> ajax = new HashMap<>();
        // 生成令牌
        String token = loginService.login( SecureUtil.aes(aesKeyPropertiesConfig.getKey().getBytes()).decryptStr(loginBody.getUsername()) , SecureUtil.aes(aesKeyPropertiesConfig.getKey().getBytes()).decryptStr(loginBody.getPassword()), loginBody.getCode(),
            loginBody.getUuid());
        ajax.put(Constants.TOKEN, token);
        return ApiResult.ok(ajax);
    }




    /**
     * 根据ticket获取用户信息  统一登录接口 返回自己的token
     *
     * @param loginBody 登录信息
     * @return 结果
     */
    @SaIgnore
    @GetMapping("/getUserInfoByTicket")
    public ApiResult<Map<String, Object>> getUserInfoByTicket(@Validated @RequestBody LoginBody loginBody) {
        Map<String, Object> ajax = new HashMap<>();

        return ApiResult.ok(ajax);
    }
    /**
     * 统一登录退出接口
     */
    @SaIgnore
    @PostMapping("/auth/logout")
    public ApiResult<Void> authLogout() {
        return ApiResult.ok("退出成功");
    }



    /**
     * 短信登录
     *
     * @param smsLoginBody 登录信息
     * @return 结果
     */
    @SaIgnore
    @PostMapping("/smsLogin")
    public ApiResult<Map<String, Object>> smsLogin(@Validated @RequestBody SmsLoginBody smsLoginBody) {
        Map<String, Object> ajax = new HashMap<>();
        // 生成令牌
        String token = loginService.smsLogin(smsLoginBody.getPhonenumber(), smsLoginBody.getSmsCode());
        ajax.put(Constants.TOKEN, token);
        return ApiResult.ok(ajax);
    }

    /**
     * 小程序登录(示例)
     *
     * @param xcxCode 小程序code
     * @return 结果
     */
    @SaIgnore
    @PostMapping("/xcxLogin")
    public ApiResult<Map<String, Object>> xcxLogin(@NotBlank(message = "{xcx.code.not.blank}") String xcxCode) {
        Map<String, Object> ajax = new HashMap<>();
        // 生成令牌
        String token = loginService.xcxLogin(xcxCode);
        ajax.put(Constants.TOKEN, token);
        return ApiResult.ok(ajax);
    }

    /**
     * 退出登录
     */
    @SaIgnore
    @PostMapping("/logout")
    public ApiResult<Void> logout() {
        loginService.logout();
        return ApiResult.ok("退出成功");
    }

    /**
     * 获取用户信息
     *
     * @return 用户信息
     */
    @GetMapping("getInfo")
    public ApiResult<Map<String, Object>> getInfo() {
        LoginUser loginUser = LoginHelper.getLoginUser();
        SysUser user = userService.selectUserById(loginUser.getUserId());
        Map<String, Object> ajax = new HashMap<>();
        ajax.put("user", user);
        ajax.put("roles", loginUser.getRolePermission());
        ajax.put("permissions", loginUser.getMenuPermission());
        return ApiResult.ok(ajax);
    }

    /**
     * 获取路由信息
     *
     * @return 路由信息
     */
    @GetMapping("getRouters")
    public ApiResult<List<RouterVo>> getRouters() {
        String userId = LoginHelper.getUserId();
        List<SysMenu> menus = menuService.selectMenuTreeByUserId(userId);
        return ApiResult.ok(menuService.buildMenus(menus));
    }
}
